const Config = require('./config')
const MongoClient = require('mongodb').MongoClient

class Db {
  constructor () {
    this._db = null
  };
  static getInstance () {
    if (!Db.instance) {
      Db.instance = new Db()
    }
    return Db.instance
  }
  // 连接
  connect () {
    return new Promise((resolve, reject) => {
      if (this._db) {
        resolve(this._db)
      } else {
        MongoClient.connect(Config.dbUrl, {
          useNewUrlParser: true
        }, (err, client) => {
          if (err) throw err
          this._db = client.db(Config.dbName)
          resolve(this._db)
        })
      }
    })
  }
  find (collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        let re = db.collection(collectionName).find(json)
        re.toArray((err, docs) => {
          if (err) throw err
          resolve(docs)
        })
      })
    })
  }
  insert (collectionName, query) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).insert(query, (err, result) => {
          if (err) throw err
          resolve(true)
        })
      })
    })
  };
  update (collectionName, json1, json2) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).update(json1, {
          $set: json2
        }, {
          multi: true
        }, (err, result) => {
          if (err) throw err
          resolve(true)
        })
      })
    })
  };
  delete (collectionName, json) {
    return new Promise((resolve, reject) => {
      this.connect().then((db) => {
        db.collection(collectionName).remove(json, (err, result) => {
          if (err) throw err
          resolve(true)
        })
      })
    })
  }
}
module.exports = Db.getInstance()
